<template>

    <div class="address-append" v-loading="loading">
        <h2 v-text="id ? 'Edit address' : 'Add address'"></h2>
        <CommonAddressForm v-model="formData" @validate="forbid = !!$event" />
        <footer>
            <button v-if="type == 'add'" :disabled="forbid" @click="doUpdate($event)" type="primary">
                Save
            </button>
            <button v-else @click="doUpdate($event)" :disabled="forbid" type="primary">
                Modify
            </button>
            <button @click="Cancel($event)">Cancel</button>
        </footer>
    </div>

</template>
<script>
import { getRules } from "@/utils/address-rules";
import Country from "@/utils/country";
import AsyncValidator from 'async-validator';
export default {
    name: "AddressBook",
    layout: "layout-user",
    data () {
        return {
            id: "",
            type: "add",
            loading: false,
            addShow: false,
            formDisable: true,
            saveAddr: "",
            country: Country,
            formData: {
                first_name: "",
                last_name: "",
                phone: "",
                email: "",
                country: "",
                country_code: "",
                state: "",
                street: "",
                district: "",
                city: "",
                post_code: "",
            },
            forbid: true,
            rules: getRules(),
        };
    },
    // watch: {
    //     formData: {
    //         immediate: true,
    //         deep: true,
    //         handler () {
    //             const descriptor = {}
    //             const address = this.formData || {};
    //             Object.keys(address).map(key => this.rules[key] && (descriptor[key] = this.rules[key]));
    //             (new AsyncValidator(descriptor)).validate(address, { suppressWarning: true }, (err, fields) => {
    //                 this.forbid = !!err
    //             })
    //         }
    //     }
    // },
    methods: {
        Cancel (event) {
            event.stopPropagation();
            event.preventDefault();
            this.$router.go(-1);
        },

        async doUpdate (event) {
            let resdata = {
                first_name: this.formData.first_name,
                phone: this.formData.phone,
                email: this.formData.email,
                country_code: this.formData.country_code,
                country: this.formData.country,
                state: this.formData.state,
                street: this.formData.street,
                district: this.formData.district,
                city: this.formData.city,
                post_code: this.formData.post_code,
            };

            let result = null;

            this.loading = true;

            if (this.id) {
                result = await this.$http("address.update/" + this.id, resdata);
            } else {
                result = await this.$http("address.insert", resdata);
            }

            if (result.code == 0) {
                this.$uxMessage({
                    offset: 40,
                    message: this.id ? 'Address changed successfully' : "Address added successfully",
                    type: "success",
                });
                this.$router.push("/settings/address");
                this.loading = false;
            } else {

                this.loading = false;
                this.$uxMessage({
                    offset: 40,
                    message: this.id ? "Failed to change address" : "Failed to add address",
                    type: "warning",
                });
            }

        },

        async getInfo (id) {
            this.type = "put";
            this.id = id;
            this.loading = true;
            let res = await this.$http("address.search/" + id);
            if (res.code == 0) {
                let data = res.data;
                Object.keys(this.formData).map((key) => {
                    this.formData[key] = data[key];
                });
                this.loading = false;
                return;
            }
            this.loading = false;
            this.$uxMessage.warning(res.msg);
        },
    },
    created () {
        let id = this.$route.query.id || null;
        id && this.getInfo(id);
    },
};
</script>
<style lang="scss" scoped>
.address-append {
    flex: 1;
    display: flex;
    flex-direction: column;
    // min-height: 100%;
    max-height: 1000px;
    background-color: #fff;
    border-radius: 8px;
    box-sizing: border-box;
    padding: 32px 48px 150px;
    & > h2 {
        height: 28px;
        font-size: 24px;

        font-weight: normal;
        color: #000000;
        line-height: 28px;
    }

    & > footer {
        margin: 34px 0 0 0;
        display: flex;
        flex-direction: row;
        align-items: center;
        justify-content: center;
        button {
            margin: 0 12px;
            &:nth-child(1) {
                width: 360px;
                height: 40px;
            }
            &:nth-child(2) {
                width: 160px;
                height: 40px;
            }
        }
    }

    &::v-deep .address-form {
        margin: 20px -24px 0;
        .el-form-item__label:before {
            display: none;
        }
        .el-form {
            .el-form-item__label {
                padding: 0;
                margin-bottom: 4px;
            }
            .el-form-item {
                margin-bottom: 24px;
            }
        }
    }
}
</style>
